﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Models;
using BLL;
using Newtonsoft.Json.Linq;

namespace GoShopping.tools
{
    /// <summary>
    /// Addressds 的摘要说明
    /// </summary>
    public class Addressds : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //0:根据用户ID进行查询
            //1:增加地址
            //2:删除
            string t = context.Request["t"].ToString();
            switch (t)
            {
                case "0":
                    getByUserID(context);
                    break;
                case "1":
                    Add(context);
                    break;
                case "2":
                    Delete(context);
                    break;
            }
        }
        //删除
        private void Delete(HttpContext context)
        {
            int ID = int.Parse(context.Request["AddressID"]);
            bool res=AddressBLL.deleteBLL(ID);
            if (res)
            {
                context.Response.Write("{\"status\":\"删除成功！\"}");
            }
            else
            {
                context.Response.Write("{\"status\":\"删除失败！\"}");
            }
        }
        //添加
        private void Add(HttpContext context)
        {
            Models.Address address = new Models.Address();
            address.UserID = int.Parse(context.Request["UserID"]);
            address.Name = context.Request["Name"].ToString();
            address.Phone = context.Request["Phone"].ToString();
            address.AddressU = context.Request["AddressU"].ToString();
            bool res=AddressBLL.addAddressBLL(address);
            if (res)
            {
                context.Response.Write("{\"status\":\"添加成功！\"}");
            }
            else
            {
                context.Response.Write("{\"status\":\"添加失败！\"}");
            }
        }

        //根据用户ID进行查询
        private void getByUserID(HttpContext context)
        {
            int ID = int.Parse(context.Request["UserID"]);
            List<Models.Address> list = AddressBLL.getByUserIDBLL(ID);
            //把数据转换为JSON格式
            JObject obj = new JObject();
            JArray array = JArray.FromObject(list);
            obj.Add("res", array);
            if (list.Count > 0)
            {

                context.Response.Write(obj);
            }
            else
            {
                context.Response.Write("{\"status\":\"没有记录！\"}");
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}